﻿using ASmile.Extend;
using ASmile.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace ASmile.Win.Forms
{
    public partial class FrmUpdateFile : FrmBaseModal
    {
        public FrmUpdateFile()
        {
            InitializeComponent();
        }

        const string HttpBoundary = "------------UpdateFileBoundary";

        class FileInfoModel
        {
            public string FullName { set; get; }

            public string FileName { set; get; }

            public long Length { set; get; }

            public DateTime CreationTime { set; get; }

            public DateTime LastWriteTime { set; get; }
        }

        List<FileInfoModel> FileList { get; } = new List<FileInfoModel>();

        private void FrmUpdateFile_Load(object sender, EventArgs e)
        {
            txtPath.Text = Config.Settings.UpdateFilePath;
            tsBtnRefesh_Click(sender, e);
        }

        private void tsBtnRefesh_Click(object sender, EventArgs e)
        {
            if (txtPath.Text.IsEmpty())
            {
                MessageBox.Show("未配置上传路径");
                return;
            }
            txtPath.Text = Config.Settings.UpdateFilePath;
            DirectoryInfo root = new DirectoryInfo(txtPath.Text);
            var files = root.GetFiles();
            FileList.Clear();

            foreach (var item in files)
            {
                var fm = new FileInfoModel
                {
                    FileName = item.Name,
                    Length = item.Length,
                    CreationTime = item.CreationTime,
                    LastWriteTime = item.LastWriteTime,
                    FullName = item.FullName
                };
                FileList.Add(fm);
            }
            dgv.BindDataSource(FileList);
        }

        private void tsBtnUpload_Click(object sender, EventArgs e)
        {
            if (!ShowQuestion("确实要上传文件,该过程可能持续较长时间?", "上传确认")) return;

            if (tsBtnUpload.Enabled == false) return;

            tsBtnUpload.Enabled = false;
            string urlRoot = $"{Config.Settings.ServerUrl}/api/Common/FileHelper/UploadUpdateFile";
            HttpHelper http = new HttpHelper();
            HttpItem argHttp = new HttpItem
            {
                PostDataType = PostDataType.Byte,
                Encoding = Encoding.UTF8,
                ContentType = $"multipart/form-data; boundary={HttpBoundary}",
                Method = "POST",
            };
            argHttp.Header.Add(Config.Settings.TokenName, TokenHelper.TokenValue); //HttpBase.TokenVal);

            StartWorking(UpladFile, UpladFileOver);

            void UpladFile()
            {
                progressBar.Value = 0;
                progressBar.Maximum = FileList.Count;
                BytesEncodeHelper byteObj = new BytesEncodeHelper();
                bool firstFile = true;
                foreach (var item in FileList)
                {
                    argHttp.URL = $"{urlRoot}?firstFile={firstFile}";

                    byteObj.ClearData();
                    byteObj
                        .AddString($"--{HttpBoundary}").AddLine()
                        .AddString($"Content-Disposition:  form-data; name=\"file\";  filename=\"{item.FileName}\"").AddLine()
                        .AddString($"Content-Type: application/octet-stream").AddLine(2);
                    var fileBytes = File.ReadAllBytes(item.FullName);
                    byteObj.AddBytes(fileBytes);
                    byteObj.AddLine().AddString($"--{HttpBoundary}--").AddLine(2);
                    argHttp.PostdataByte = byteObj.GetResult().ToArray();
                    var r = http.GetHtml(argHttp);
                    if (r.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        MessageBox.Show($"请求地址错误, code:{(int)r.StatusCode}, msg: {r.StatusDescription} ");
                        return;
                    }
                    var ret = JsonHelper.JsonToObject<ApiResult>(r.Html);
                    if (!ret)
                    {
                        MessageBox.Show(ret.msg);
                        break;
                    }
                    progressBar.Value++;
                    firstFile = false;
                }
                ShowMessage("上传升级文件完成");
            }

            void UpladFileOver()
            {
                tsBtnUpload.Enabled = true;
                progressBar.Value = progressBar.Maximum;

            }
        }

        private void tsbtnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmUpdateFile_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (tsBtnUpload.Enabled == false)
            {
                ShowMessage("正在上传升级文件, 请稍后退出");
                e.Cancel = true;
                return;
            }
        }
    }
}